<?php

namespace addons\shopro\controller\user;

use addons\shopro\service\lucky\RecordService;
use app\admin\model\shopro\app\Update;
use app\common\library\Sms;
use addons\shopro\controller\Common;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\order\Aftersale as AftersaleModel;
use app\admin\model\shopro\ThirdOauth;

class User extends Common
{

    protected $noNeedLogin = ['smsRegister', 'accountLogin', 'smsLogin', 'resetPassword','accountRegister','dowonLoad', 'accountPay'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        \think\Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');        // 加载语言包
    }

    /**
     * 用户数据
     */
    public function data()
    {
        $user = auth_user();
        // 查询用户优惠券数量
        $data['coupons_num'] = UserCouponModel::geted()->where('user_id', $user->id)->count();

        // 订单数量
        $orderNum = [];
        $orderNum['unpaid'] = OrderModel::where('user_id', $user->id)->unpaid()->count();
        $orderNum['nosend'] = OrderModel::where('user_id', $user->id)->pretendPaid()->nosend()->count();
        $orderNum['noget'] = OrderModel::where('user_id', $user->id)->pretendPaid()->noget()->count();
        $orderNum['nocomment'] = OrderModel::where('user_id', $user->id)->paid()->nocomment()->count();
        $orderNum['aftersale'] = AftersaleModel::where('user_id', $user->id)->needOper()->count();

        $data['order_num'] = $orderNum;

        $this->success('用户数据', $data);
    }

    /**
     * 第三方授权信息
     */
    public function thirdOauth()
    {
        $user = auth_user();

        $provider = $this->request->param('provider', '');
        $platform = $this->request->param('platform', '');
        if (!in_array($platform, ['miniProgram', 'officialAccount', 'openPlatform'])) {
            $this->error(__('Invalid parameters'));
        }
        $where = [
            'platform' => $platform,
            'user_id' => $user->id
        ];
        if ($provider !== '') {
            $where['provider'] = $provider;
        }
        $oauth = ThirdOauth::where($where)->field('nickname, avatar, platform, provider')->find();
        $this->success('', $oauth);
    }


    /**
     * 用户信息
     */
    public function profile()
    {
        //TODO @ldh: 1.账号被禁用 2.连表查group
        $user = auth_user(true);

        $user = UserModel::with(['parent_user', 'third_oauth'])->where('id', $user->id)->find();

        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);

        $this->success('个人详情', $user);
    }

    /**
     * 更新用户资料
     */
    public function update()
    {
        $user = auth_user();

        $params = $this->request->only(['avatar', 'nickname', 'gender']);
        $this->svalidate($params);

        $user->save($params);
        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);

        $this->success('更新成功', $user);
    }

    /**
     * 账号密码登录
     */
    public function accountLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['account', 'password']);
        $this->svalidate($params, '.accountLogin');

        $ret = $this->auth->login($params['account'], $params['password']);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '注册失败');
        }
    }


    public function accountPay()
    {
//        \think\Log::record("回调开始");
        $allParams = $this->request->param();
        \think\Log::info(json_encode($allParams));

        $sign_src = $allParams['sign'];
        \think\Log::info("接受到的sign：".$sign_src);
        unset($allParams['sign']);
        unset($allParams['addon']);
        unset($allParams['controller']);
        unset($allParams['action']);
        ksort($allParams);
        $api_key= 'gxJZ2PB73gGOPq9uYTcmPQDnSGRU78JP1Z0v5hyAgde6nipJHNpxqZHjKRZkf74a0486zzwUcosnyuGs87h8fDX21NR53ruHIU2BvuTnVVWcuUboDm0XKmfPGPY588jn';


        $singStr = '';
        foreach ($allParams as $key => $value) {
            $singStr .= $key . '=' . $value . '&';
        }
        $singStr .= "key=".$api_key;

        $sign = strtoupper(md5($singStr));

        \think\Log::info("签名sign：".$sign);

        if($sign_src != $sign) {
            return 'FAIL0';
        }

        $orderNo = $allParams['mchOrderNo'];

        $model = new \app\admin\model\shopro\lucky\Record;

//        $row = $model->where('order_num', $orderNo)->where('status', 0)->find();
        $row = (new RecordService())->getOrderByNo($orderNo);
        \think\Log::info("订单信息".print_r($row->toArray(), 1));

        if (!$row) {
            return 'FAIL1';
        }
        \think\Log::info("有订单".$sign);
        //金额对比
        if ($row['account'] != $allParams['amount'] / 100) {
            return 'FAIL2';
        }
        \think\Log::info("金额正确".$sign);
        if((new RecordService())->setStatus($row['id'],'1')) {
            $row['outTransactionId'] = $allParams['outTransactionId'];
            $row->save();
            \think\Log::info("充值成功".$sign);
            return 'SUCCESS';
        }

        return 'FAIL3';

//        \think\Log::record("计算出来的sign：".$sign);
        /* array (
   'amount' => '2',
   'body' => '纸巾2包',
   'channelUser' => '2088302393237297',
   'currency' => 'CNY',
   'mchFeeAmount' => '0',
   'mchNo' => 'M25101000031',
   'mchOrderNo' => 'M251010000311760193720',
   'officOrderNo' => '2025101122001437291448772052',
   'outTransactionId' => '2025101102242277482154920211402',
   'payOrderId' => 'P1977021872631369729',
   'sign' => '1E2B516DF00916490204EF544C16EB5A',
   'state' => 2,
   'storeId' => '15012',
   'subject' => '商户智能收银',
   'successTime' => '1760193752000',
   'wayCode' => 'ALI_JSAPI',
   'addon' => 'shopro',
   'controller' => 'user.user',
   'action' => 'accountPay',
 )*/
        //$jsonParams = $this->request->json();
        //\think\Log::record(json_encode($jsonParams));


//        \think\Log::record("回调结束");
//
//        return 'success';

    }



    /***
     * @notes:用户名注册
     * @author: 小谢
     * @date: 2024/9/7 13:05
     */
    public function accountRegister()
    {
        $user = auth_user();
        if ($user) {
            $this->error('您已登录,请先退出登录');
        }
        $params = $this->request->only(['username', 'invitation', 'password','rep_password']);
        $this->svalidate($params, '.userRegister');

        $userAuth = new UserAuth();
        $auth = $userAuth->register($params);
        set_token_in_header($auth->getToken());

        $this->success(__('Sign up successful'));

    }

    /**
     * 短信验证码登陆
     */
    public function smsLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.smsLogin');
        if (!Sms::check($params['mobile'], $params['code'], 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = UserModel::getByMobile($params['mobile']);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }else {
            $this->error('该手机号暂未注册');
        }
        if (isset($ret) && $ret) {
            Sms::flush($params['mobile'], 'mobilelogin');
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '登录失败');
        }
    }

    /**
     * 短信验证码注册
     */
    public function smsRegister()
    {
        $user = auth_user();
        if ($user) {
            $this->error('您已登录,请先退出登录');
        }

        $params = $this->request->only(['mobile', 'code', 'password']);
        $this->svalidate($params, '.smsRegister');

        $ret = Sms::check($params['mobile'], $params['code'], 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        // 注册
        $userAuth = new UserAuth();
        $auth = $userAuth->register($params);
        set_token_in_header($auth->getToken());

        $this->success(__('Sign up successful'));
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $user = auth_user();

        $params = $this->request->only(['oldPassword', 'newPassword']);
        $this->svalidate($params, '.changePassword');

        $userAuth = new UserAuth();
        $userAuth->changePassword($params['newPassword'], $params['oldPassword']);

        $this->auth->direct($user->id);
        set_token_in_header($this->auth->getToken());

        $this->success(__('Change password successful'));
    }

    /**
     * 重置/忘记密码
     */
    public function resetPassword()
    {
        $params = $this->request->only(['username','mobile', 'code', 'password']);
        $this->svalidate($params, '.resetPassword');

        $ret = Sms::check($params['mobile'], $params['code'], 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->resetPassword($params);

        $this->success(__('Reset password successful'));
    }

    /***
     * 重置支付密码
     * @return void
     */
    public function resetRepPassword()
    {

        $params = $this->request->only(['mobile', 'code', 'rep_password']);
        $this->svalidate($params, '.resetRepPassword');
        $user = auth_user();
        if($user->mobile!=$params['mobile']){
            $this->error('该账户与手机号不匹配！');
        }
        $ret = Sms::check($params['mobile'], $params['code'], 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        if($this->auth->changereppwd($params['rep_password'])){
            $this->success(__('Reset password successful'));
        }
        $this->error('支付密码修改失败！');
    }


    /**
     * 更换手机号
     */
    public function changeMobile()
    {
        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.changeMobile');

        $ret = Sms::check($params['mobile'], $params['code'], 'changemobile');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->changeMobile($params);

        $this->success('绑定成功');
    }

    /**
     * 修改用户名
     */
    public function changeUsername()
    {
        $user = auth_user(true);

        $params = $this->request->only(['username']);
        $this->svalidate($params, '.changeUsername');

        $userAuth = new UserAuth();
        $userAuth->changeUsername($params);

        $this->success('绑定成功');
    }

    /**
     * 更新小程序头像和昵称
     */
    public function updateMpUserInfo()
    {
        $user = auth_user(true);

        $params = $this->request->only(['avatar', 'nickname']);
        $this->svalidate($params, '.updateMpUserInfo');

        $user->save($params);

        $thirdOauth = \app\admin\model\shopro\ThirdOauth::where('user_id', $user->id)->where([
            'provider' => 'wechat',
            'platform' => 'miniProgram'
        ])->find();
        $thirdOauth->save($params);
        $this->success('绑定成功');
    }



    /**
     * 登出
     */
    public function logout()
    {
        $userAuth = new UserAuth();
        $userAuth->logout();

        $this->success(__('Logout successful'));
    }


    /**
     * 用户注销
     */
    public function logoff()
    {
        $userAuth = new UserAuth();
        $userAuth->logoff();

        $this->success('注销成功');
    }

    public function dowonLoad()
    {
        $config = Update::where(['stutas'=>1])->order('createtime','DESC')->find();
        return $this->success('ok',$config);
    }
}
